package com.lichuandi.anno;

import java.lang.reflect.Method;

// 处理注解
public class AnnotationProcessor {
    public static void processAnnotations(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();

        // 类级别注解
        if (clazz.isAnnotationPresent(Loggable.class)) {
            Loggable loggable = clazz.getAnnotation(Loggable.class);
            System.out.println("Class is loggable: " + loggable.value());
        }

        // 方法级别注解
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Loggable.class)) {
                Loggable methodLoggable = method.getAnnotation(Loggable.class);
                System.out.println("Method " + method.getName() + " is loggable: " + methodLoggable.value());

                if (methodLoggable.trackTime()) {
                    long start = System.currentTimeMillis();
                    invokeMethodWithDefaultValues(method, obj);
                    long duration = System.currentTimeMillis() - start;
                    System.out.println("Method execution took " + duration + "ms");
                } else {
                    invokeMethodWithDefaultValues(method, obj);
                }
            }
        }
    }

    private static void invokeMethodWithDefaultValues(Method method, Object obj) throws Exception {
        Class<?>[] paramTypes = method.getParameterTypes();
        Object[] args = new Object[paramTypes.length];
        for (int i = 0; i < paramTypes.length; i++) {
            if (paramTypes[i] == String.class) {
                args[i] = "default";
            } else if (paramTypes[i] == int.class || paramTypes[i] == Integer.class) {
                args[i] = 0;
            } else if (paramTypes[i] == boolean.class || paramTypes[i] == Boolean.class) {
                args[i] = false;
            }
            // 可以添加更多基本类型的默认值处理
        }
        method.invoke(obj, args);
    }
}